<template>
  <div class="app-container">
    <div class="sidebar-container" :class="{ 'is-collapsed': isCollapse }">
      <Sidebar :is-collapse="isCollapse" />
    </div>
    
    <div class="main-container">
      <header class="app-header">
        <el-button 
          link
          class="toggle-button" 
          @click="toggleSidebar"
        >
          <el-icon v-if="isCollapse"><Expand /></el-icon>
          <el-icon v-else><Fold /></el-icon>
        </el-button>
        
        <div class="header-right">
          <div class="message-indicator" v-if="unreadMessageCount > 0 && !isAdminOrCustomer" @click="goToMessages">
            <el-badge :value="unreadMessageCount" class="message-badge">
              <el-icon><ChatDotSquare /></el-icon>
            </el-badge>
          </div>
          
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="user-dropdown">
              {{ username }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="!isAdminOrCustomer" command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item v-if="!isAdminOrCustomer" command="messages">我的消息</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>
      
      <main class="app-main">
        <router-view />
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Expand, Fold, ArrowDown, ChatDotSquare } from '@element-plus/icons-vue'
import Sidebar from './Sidebar.vue'
import { getUnreadMessageCount } from '@/api/message'

const router = useRouter()
const isCollapse = ref(false)
const username = ref(localStorage.getItem('username') || '用户')
const unreadMessageCount = ref(0)
let messageTimer = null
const userType = ref(localStorage.getItem('userType') || '')

// 判断是否为管理员或客服
const isAdminOrCustomer = computed(() => {
  return userType.value === 'admin' || userType.value === 'customer'
})

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

const goToProfile = () => {
  router.push('/profile')
}

const goToMessages = () => {
  router.push('/messages')
}

const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('username')
  localStorage.removeItem('userType')
  localStorage.removeItem('userId')
  
  // 清除定时器
  if (messageTimer) {
    clearInterval(messageTimer)
  }
  
  router.push('/login')
}

const handleCommand = (command) => {
  if (command === 'profile') {
    goToProfile()
  } else if (command === 'messages') {
    goToMessages()
  } else if (command === 'logout') {
    logout()
  }
}

// 获取未读消息数量
const fetchUnreadMessageCount = () => {
  // 如果是管理员或客服，不获取消息数量
  if (isAdminOrCustomer.value) {
    return
  }
  
  getUnreadMessageCount()
    .then(response => {
      if (response && response.code === 200) {
        unreadMessageCount.value = response.data || 0
      }
    })
    .catch(error => {
      console.error('获取未读消息数量失败:', error)
    })
}

onMounted(() => {
  // 初始获取未读消息数量
  fetchUnreadMessageCount()
  
  // 定时刷新未读消息数量（每30秒）
  messageTimer = setInterval(fetchUnreadMessageCount, 30000)
})

onBeforeUnmount(() => {
  // 组件卸载前清除定时器
  if (messageTimer) {
    clearInterval(messageTimer)
  }
})
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.sidebar-container {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  width: 220px;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(5px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
  height: 100%;
}

.sidebar-container.is-collapsed {
  width: 64px;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100vh;
  width: calc(100vw - 220px);
}

.sidebar-container.is-collapsed + .main-container {
  width: calc(100vw - 64px);
}

.app-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.toggle-button {
  font-size: 20px;
  color: #6a5acd;
  transition: all 0.3s;
}

.toggle-button:hover {
  color: #6a11cb;
  transform: scale(1.1);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.message-indicator {
  cursor: pointer;
  font-size: 18px;
  color: #6a5acd;
  transition: all 0.3s;
}

.message-indicator:hover {
  color: #6a11cb;
  transform: scale(1.1);
}

.message-badge :deep(.el-badge__content) {
  background: linear-gradient(to right, #ff8a00, #e52e71);
  border: none;
  font-weight: bold;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #5a5a5a;
  font-weight: 500;
  transition: all 0.3s;
}

.user-dropdown:hover {
  color: #6a11cb;
}

.user-dropdown .el-icon {
  margin-left: 5px;
  color: #6a5acd;
}

.el-dropdown-menu {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  border: none;
}

.el-dropdown-menu :deep(.el-dropdown-menu__item) {
  color: #5a5a5a;
  transition: all 0.3s;
}

.el-dropdown-menu :deep(.el-dropdown-menu__item):hover {
  background: linear-gradient(to right, rgba(106, 17, 203, 0.1), rgba(37, 117, 252, 0.1));
  color: #6a11cb;
}

.app-main {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  position: relative;
  height: calc(100vh - 60px);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .sidebar-container:not(.is-collapsed) {
    position: absolute;
    z-index: 100;
  }
  
  .sidebar-container.is-collapsed + .main-container {
    width: 100vw;
  }
  
  .header-right {
    gap: 15px;
  }
}
</style>